import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import axios from "axios";

export const login = createAsyncThunk("user", async (xx) => {
  // console.log(xx);
  const { data } = await axios.post("http://localhost:5000/login", xx);
  // 做判断，data.code === 0
  if (data.code === 0) {
    // fulfilled
    return data;
  } else {
    // rejected
    return Promise.reject(new Error(data.msg));
  }
});

// const userStr = window.localStorage.getItem("user");
// const userOjb = userStr ? JSON.parse(userStr) : {};
// const userInfo = userOjb.userInfo || {};

const userSlice = createSlice({
  name: "user",
  initialState: {
    userId: "",
    username: "",
    token: "",
  },
  reducers: {
    // 登录成功
    loginSuccess(state, { payload }) {
      console.log("loginSuccess", payload);
      state.userId = payload.userInfo.userId;
      state.username = payload.userInfo.username;
      state.token = payload.token;
    },
  },
  extraReducers: {
    [login.pending]() {
      console.log("login.pending");
    },
    [login.fulfilled](state, { payload }) {
      console.log("login.fulfilled", payload);
      // 上面做了判断，这边就不需要再判断了
      state.userId = payload.data.userInfo.userId;
      state.username = payload.data.userInfo.username;

      // // 判断是否登录成功
      // if (payload.code === 0) {
      //   // 登录成功
      //   state.userId = payload.data.userInfo.userId;
      //   state.username = payload.data.userInfo.username;
      // } else {
      //   // 登录失败
      //   return Promise.reject("登录失败");
      // }
    },
    [login.rejected](state, { error }) {
      console.log("login.rejected");
      throw error;
    },
  },
});

export const { loginSuccess } = userSlice.actions;

export default userSlice.reducer;
